package com.jeesite.modules.ocr.web;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.io.FileUtils;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONValidator;
import com.benjaminwan.ocrlibrary.OcrResult;
import com.benjaminwan.ocrlibrary.TextBlock;
import com.beust.jcommander.internal.Lists;
import com.jeesite.common.codec.EncodeUtils;
import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.ocr.entity.OcrTemplate;
import com.jeesite.modules.ocr.entity.OcrTextBlock;
import com.jeesite.modules.file.entity.FileUpload;
import com.jeesite.modules.file.utils.FileUploadUtils;
import com.jeesite.modules.ocr.adapter.OcrResultFactory;
import com.jeesite.modules.ocr.base.IOcrResult;
import com.jeesite.modules.ocr.entity.OcrAlgorithmConfig;
import com.jeesite.modules.ocr.entity.OcrTempateConfigs;
import com.jeesite.modules.ocr.service.OcrAlgorithmConfigService;
import com.jeesite.modules.ocr.service.OcrTemplateService;
import com.jeesite.modules.ocr.utils.OCRImageUtils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import io.github.mymonstercat.ocr.InferenceEngine;
import io.github.mymonstercat.ocr.config.ParamConfig;

/**
 * 模板管理Controller
 * 
 * @author 姚海陆,长春叭哥
 * @version 2024-07-29
 */
@Controller
@RequestMapping(value = "${adminPath}/ocr/ocrTemplate")
public class OcrTemplateController extends BaseController {
	@Autowired
	private OcrAlgorithmConfigService ocrAlgorithmConfigService;
	@Autowired
	private OcrTemplateService ocrTemplateService;

	/**
	 * 获取数据
	 */
	@ModelAttribute
	public OcrTemplate get(String ocrTemplateId, boolean isNewRecord) {
		return ocrTemplateService.get(ocrTemplateId, isNewRecord);
	}

	/**
	 * 管理主页
	 */
	@RequiresPermissions("ocr:ocrTemplate:view")
	@RequestMapping(value = "index")
	public String index(OcrTemplate ocrTemplate, Model model) {
		model.addAttribute("ocrTemplate", ocrTemplate);
		return "modules/ocr/ocrTemplateIndex";
	}

	/**
	 * 管理主页
	 * 
	 * @throws IOException
	 */
	@SuppressWarnings("null")
	@RequiresPermissions("ocr:ocrTemplate:view")
	@RequestMapping(value = "ocrRecImage")
	@ResponseBody
	public String ocrRecImage(String id, String tempateImage, String imageId, Model model) throws IOException {
		OcrTemplate ocrTemplate = ocrTemplateService.get(id);
		if (ocrTemplate == null || StringUtils.isEmpty(ocrTemplate.getId())) {
			return renderResult(Global.FALSE, text("图片OCR解析失败！"));
		}
		ocrTemplate.setTempateImage(tempateImage);
		FileUpload fileUpload = FileUploadUtils.getFileUploadService().get(imageId);
		if (fileUpload == null) {
			return renderResult(Global.FALSE, text("解析失败，请先上传模板图片！"), model);
		}
		OcrAlgorithmConfig ocrAlgorithmConfig = ocrAlgorithmConfigService.get("1");
		IOcrResult iOcrResult=OcrResultFactory.getOcrResult(ocrAlgorithmConfig);
		List<OcrTextBlock> needTextBlocks=iOcrResult.process(fileUpload, ocrAlgorithmConfig);
		model.addAttribute("tempateImage", ocrTemplate.getTempateImage());
		model.addAttribute("ocrTempateConfigsList", OcrTempateConfigs.getListOcrTempateConfigs(needTextBlocks));
		model.addAttribute("ocrTemplate", ocrTemplate);
		model.addAttribute("ocrResult", needTextBlocks);
		model.addAttribute("tempateImageRec",ocrTemplate.getTempateImageRec());
		return renderResult(Global.TRUE, text("图片OCR解析成功！"), model);
	}

	/**
	 * 查询列表
	 */
	@RequiresPermissions("ocr:ocrTemplate:view")
	@RequestMapping(value = { "list", "" })
	public String list(OcrTemplate ocrTemplate, Model model) {
		model.addAttribute("ocrTemplate", ocrTemplate);
		return "modules/ocr/ocrTemplateList";
	}

	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("ocr:ocrTemplate:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<OcrTemplate> listData(OcrTemplate ocrTemplate, HttpServletRequest request,
			HttpServletResponse response) {
		ocrTemplate.setPage(new Page<>(request, response));
		Page<OcrTemplate> page = ocrTemplateService.findPage(ocrTemplate);
		return page;
	}

	/**
	 * 查询子表数据
	 */
	@RequiresPermissions("ocr:ocrTemplate:view")
	@RequestMapping(value = "ocrTempateConfigsListData")
	@ResponseBody
	public Page<OcrTempateConfigs> subListData(OcrTempateConfigs ocrTempateConfigs, HttpServletRequest request,
			HttpServletResponse response) {
		ocrTempateConfigs.setPage(new Page<>(request, response));
		Page<OcrTempateConfigs> page = ocrTemplateService.findSubPage(ocrTempateConfigs);
		return page;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("ocr:ocrTemplate:view")
	@RequestMapping(value = "form")
	public String form(OcrTemplate ocrTemplate, Model model) {
		model.addAttribute("ocrTemplate", ocrTemplate);
		return "modules/ocr/ocrTemplateForm";
	}

	/**
	 * 保存数据
	 */
	@RequiresPermissions("ocr:ocrTemplate:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated OcrTemplate ocrTemplate) {
		ocrTemplateService.save(ocrTemplate);
		return renderResult(Global.TRUE, text("保存模板管理成功！"));
	}

	/**
	 * 停用数据
	 */
	@RequiresPermissions("ocr:ocrTemplate:edit")
	@RequestMapping(value = "disable")
	@ResponseBody
	public String disable(OcrTemplate ocrTemplate) {
		ocrTemplate.setStatus(OcrTemplate.STATUS_DISABLE);
		ocrTemplateService.updateStatus(ocrTemplate);
		return renderResult(Global.TRUE, text("停用模板管理成功"));
	}

	/**
	 * 启用数据
	 */
	@RequiresPermissions("ocr:ocrTemplate:edit")
	@RequestMapping(value = "enable")
	@ResponseBody
	public String enable(OcrTemplate ocrTemplate) {
		ocrTemplate.setStatus(OcrTemplate.STATUS_NORMAL);
		ocrTemplateService.updateStatus(ocrTemplate);
		return renderResult(Global.TRUE, text("启用模板管理成功"));
	}

	/**
	 * 删除数据
	 */
	@RequiresPermissions("ocr:ocrTemplate:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(OcrTemplate ocrTemplate) {
		ocrTemplateService.delete(ocrTemplate);
		return renderResult(Global.TRUE, text("删除模板管理成功！"));
	}

	/**
	 * 列表选择对话框
	 */
	@RequiresPermissions("ocr:ocrTemplate:view")
	@RequestMapping(value = "ocrTemplateSelect")
	public String ocrTemplateSelect(OcrTemplate ocrTemplate, String selectData, Model model) {
		String selectDataJson = EncodeUtils.decodeUrl(selectData);
		if (selectDataJson != null && JSONValidator.from(selectDataJson).validate()) {
			model.addAttribute("selectData", selectDataJson);
		}
		model.addAttribute("ocrTemplate", ocrTemplate);
		return "modules/ocr/ocrTemplateSelect";
	}

}